<?php

class ImportCsvForm extends CFormModel
{
	public $file;
	public $delim = ',';
	public $realDelim = ',';

	public function rules()
	{
		return array(
			array('file', 'file', 'types' => array('txt', 'csv')),
			array('delim', 'required'),
			array('delim', 'checkDelimiter'),
		);
	}

	public function checkDelimiter($attribute, $params)
	{
		$value = $this->$attribute;
		if (strlen($value) === 1) {
			$this->realDelim = $value;
		} elseif (strlen($value) > 1) {
			if ($value === '\t') {
				$this->realDelim = "\t";
			} elseif (strlen($value) === 4 && substr($value, 0, 2) === '\x') {
				$this->realDelim = chr(hexdec(substr($value, 2, 2)));
			} else {
				$this->addError($attribute, '分隔符只允许一个字符，或采用 \t 及 \xHH 形式表示');
			}
		}
	}

	public function attributeLabels()
	{
		return array(
			'file' => '要导入的文件',
			'delim' => '字段分隔符',
		);
	}
}
